

//图像处理模块


//rgb565 转   灰度


module RGB565_2_GRAY(

	input					clk,
	input					rst,
	
	
	
	input					data_en,				//sdram读取数据有效
	output				write_en,			//写入fifo有效
	
	
	
	input[15:0]			data_in,				//sdram读取到的数据
	output[15:0]		data_out				//转为灰度输出
);



reg[7:0]	reg_R;
reg[7:0]	reg_G;
reg[7:0]	reg_B;


reg[7:0]	reg_RGB;


reg	delay_en1;
reg 	delay_en2;
reg   delay_en3;




assign data_out = {reg_RGB,reg_RGB};
assign write_en = delay_en2;

//计算rgb三个值
always@(posedge clk or negedge rst)
begin
	if(rst == 1'b0)
	begin
		reg_R <= 'd0;
		reg_G	<= 'd0;
		reg_B <= 'd0;
	end
	else	if(data_en == 1'b1)
	begin
		reg_R <= {data_in[15:11],3'b0};
		reg_G	<= {data_in[10:5],2'b0};
		reg_B <= {data_in[4:0],3'b0};
	end
	else
	begin
		reg_R <= reg_R;
		reg_G	<= reg_G;
	   reg_B <= reg_B;
	end
end


//计算regR regB  regG之和
always@(posedge clk or negedge rst)
begin
	if(rst == 1'b0)
		reg_RGB <= 'd0;
	else
		reg_RGB <= (reg_R + reg_G + reg_B)/3;  //取平均值
end

//延时两个en周期
always@(posedge clk or negedge rst)
begin
	if(rst == 1'b0)
	begin
		delay_en1 <= 1'b0;
		delay_en2 <= 1'b0;
	end

	else	
	begin
		delay_en1 <= data_en;
		delay_en2 <= delay_en1;
	end
end


endmodule 